<template>
  <div class="highlighted-text p-10">
    <template v-for="(char, index) in textChars" :key="index">
      <el-tooltip
        v-if="highlightMap[index]?.length"
        effect="dark"
        placement="top"
        :content="getTooltipContent(index)"
        raw-content
      >
        <span :class="getHighlightClass(index)">{{ char }}</span>
      </el-tooltip>
      <template v-else>{{ char }}</template>
    </template>
  </div>
</template>

<script setup>
import { computed } from "vue";

const props = defineProps({
  text: {
    type: String,
    required: true,
  },
  details: {
    type: Array,
    default: () => [],
  },
});

// 将文本转换为字符数组
const textChars = computed(() => props.text.split(""));

// 构建高亮位置映射表（修复：合并相同位置的多个违规类型）
const highlightMap = computed(() => {
  const map = {};
  props.details?.forEach((detail) => {
    detail.segments?.forEach((segment) => {
      const start = segment.position[0];
      const end = segment.position[segment.position.length - 1];
      for (let i = start; i <= end; i++) {
        if (!map[i]) map[i] = [];
        // 检查是否已存在相同类型的违规
        const existingIndex = map[i].findIndex((item) => item.type === detail.label);
        if (existingIndex === -1) {
          map[i].push({
            type: detail.label,
            confidence: detail.confidence,
            suggestion: detail.suggestion,
          });
        } else {
          // 保留置信度更高的结果
          if (detail.confidence > map[i][existingIndex].confidence) {
            map[i][existingIndex] = {
              type: detail.label,
              confidence: detail.confidence,
              suggestion: detail.suggestion,
            };
          }
        }
      }
    });
  });
  return map;
});

// 获取标签的友好文本
const getLabelText = (label) => {
  const labelMap = {
    terrorism: "暴恐",
    porn: "色情",
    ban: "违禁",
    abuse: "辱骂",
    ad: "广告",
    customized: "自定义",
    politics: "政治敏感",
    image_text: "图文审核",
  };
  return labelMap[label] || label;
};

// 获取建议的友好文本
const getSuggestionText = (suggestion) => {
  const suggestionMap = {
    block: "不通过",
    pass: "通过",
    review: "人工复检",
  };
  return suggestionMap[suggestion] || suggestion;
};

// 获取tooltip内容（优化换行显示）
const getTooltipContent = (index) => {
  const items = highlightMap.value[index] || [];
  return items
    .map(
      (item) =>
        `违规类型: <strong>${getLabelText(item.type)}</strong>\n` +
        `置信度: <em>${(item.confidence * 100).toFixed(2)}%</em>\n` +
        `建议: <span style="color:${getSuggestionColor(item.suggestion)}">${getSuggestionText(
          item.suggestion
        )}</span>`
    )
    .join('\n<hr style="margin:4px 0;border:none;border-top:1px dashed #666;">\n');
};

// 获取建议文本颜色
const getSuggestionColor = (suggestion) => {
  const colorMap = {
    block: "#ff4d4f",
    pass: "#52c41a",
    review: "#faad14",
  };
  return colorMap[suggestion] || "#333";
};

// 获取高亮样式类（修复：支持多个类型同时显示）
const getHighlightClass = (index) => {
  const types = highlightMap.value[index]?.map((item) => item.type) || [];
  const classObj = {
    "highlight-char": true,
    "highlight-multiple": types.length > 1,
  };

  // 为每个类型添加对应的样式类
  types.forEach((type) => {
    classObj[`highlight-${type}`] = true;
  });

  return classObj;
};

// 获取主要违规类型（用于确定优先级颜色）
const getPrimaryType = (types) => {
  const priorityOrder = [
    "terrorism",
    "politics",
    "abuse",
    "porn",
    "ban",
    "ad",
    "customized",
    "image_text",
  ];

  for (const type of priorityOrder) {
    if (types.includes(type)) {
      return type;
    }
  }
  return types[0]; // 默认返回第一个
};
</script>

<style scoped>
/* 添加tooltip内容样式 */
:deep(.el-tooltip__popper) {
  white-space: pre-line; /* 保留换行 */
  max-width: 300px;
  line-height: 1.6;
}

:deep(.el-tooltip__popper hr) {
  margin: 4px 0;
  border: none;
  border-top: 1px dashed #666;
}

:deep(.el-tooltip__popper strong) {
  color: #1890ff;
}

:deep(.el-tooltip__popper em) {
  color: #722ed1;
  font-style: normal;
}

.highlighted-text {
  line-height: 1.5;
  white-space: pre-wrap;
  color: var(--prompt-text-color);
}

.highlight-char {
  padding: 0 1px;
  position: relative;
  border-radius: 2px;
  transition: all 0.2s;
}

/* 单个类型样式 */
.highlight-abuse {
  background-color: rgba(255, 205, 210, 0.7) !important;
  border-bottom: 2px solid #f44336 !important;
}

.highlight-porn {
  background-color: rgba(244, 143, 177, 0.7) !important;
  border-bottom: 2px solid #e91e63 !important;
}

.highlight-terrorism {
  background-color: rgba(255, 138, 128, 0.7) !important;
  border-bottom: 2px solid #d32f2f !important;
}

.highlight-politics {
  background-color: rgba(255, 152, 0, 0.7) !important;
  border-bottom: 2px solid #ff9800 !important;
}

.highlight-ban {
  background-color: rgba(255, 171, 145, 0.7) !important;
  border-bottom: 2px solid #ff5722 !important;
}

.highlight-ad {
  background-color: rgba(255, 224, 178, 0.7) !important;
  border-bottom: 2px solid #ff9800 !important;
}

.highlight-customized {
  background-color: rgba(197, 225, 165, 0.7) !important;
  border-bottom: 2px solid #8bc34a !important;
}

.highlight-image_text {
  background-color: rgba(100, 181, 246, 0.7) !important;
  border-bottom: 2px solid #2196f3 !important;
}

/* 多个类型时的特殊样式 */
.highlight-multiple {
  background-color: rgba(255, 193, 7, 0.7) !important;
  border-bottom: 2px dotted #ffc107 !important;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.8;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.8;
  }
}

/* 确保样式优先级 */
.highlight-char[class*="highlight-"] {
  background-color: var(--highlight-bg, inherit);
  border-bottom: var(--highlight-border, none);
}
</style>
